import requests
from pyquery import PyQuery as pq
from urllib.request import urlretrieve

def getPage(url):
	'''获取购物车网页信息'''
	# 伪装头信息	
	head = {
		'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
		'Accept-Encoding':'gzip, deflate, br',
		'Accept-Language':'zh-CN,zh;q=0.9',
		'Cache-Control':'max-age=0',
		'Connection':'keep-alive',
		'Cookie':'user-key=75b4931a-cfdb-4fc3-9f53-cae55668b4d0; shshshfpa=33fc9a0b-9584-759c-b2ea-72637426916d-1544009919; __jdv=122270672|direct|-|none|-|1544009919832; shshshfpb=1cc887d9f4abd473d9eef2cef75077e6c8145465ca329755c5c07b8c19; __jdu=154400991983123861277; PCSYCityID=1; ipLoc-djd=1-72-4137-0; areaId=1; __jda=122270672.154400991983123861277.1544009920.1544012106.1544094682.3; __jdc=122270672; 3AB9D23F7A4B3C9B=5ZWVUJY3DRZRIBANHLABVHSBBU5YA6PWU2S3ZNHPXYPRG4LKA27HV56DZ3W3YT7DIGBQJRRB4G4GDHWRNFBNR2IJIM; cart-main=xx; _gcl_au=1.1.1722534526.1544095118; wlfstk_smdl=zaa4hkjrfbmz2jay5jol3gqgs9w53un3; cn=4; cd=0; shshshfp=5509358d142b125d6c5c2177b17380de; shshshsID=dc7d15e6c1fd854de772af74909c5230_27_1544096297174; __jdb=122270672.44.154400991983123861277|3.1544094682',
		'Host':'cart.jd.com',
		'Upgrade-Insecure-Requests':'1',
		'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'
	}
	try:
		html = requests.get(url,headers=head)
		if html.status_code == 200:
			res = html.text		
			return res
		else:
			return None
	except Exception:
		return None
def parsePage(content):
	'''解析网页信息'''
	html = pq(content)
	# 获取购物车内所有商品信息
	items = html.find("div.item-item").items()
	m = 1
	for item in items:	
		# 获取购物车内商品所属的店铺名
		shop = item.parents("div.cart-tbody").find("div.shop span a.shop-name").text()
		# 获取购物车内商品名称
		good = item.find("div.item-msg div.p-name a").text()
		# 获取购物车内商品图片链接
		pic = item.find("div.p-img img").attr('src')
		# 获取购物车内商品单价
		price = item.find("p.plus-switch").text()
		# 获取购物车内商品数量
		num = item.find("div.quantity-form input").attr('value')
		# 获取购物车内商品描述
		tp = item.find("div.p-props").text().replace("\n","\t")	
		print("第"+str(m)+"条记录:\n("+shop+") "+good+"\n金额:"+price+"  数量:"+num+"件  "+tp+"\n"+"商品图片："+pic+"\n")
		m = m + 1

def main(url):
	content = getPage(url)
	if content:
		parsePage(content)
		

if __name__ == '__main__':
	url = "https://cart.jd.com/cart.action"
	main(url)
	


